package com.tanhua.server.service;

import cn.hutool.core.bean.BeanUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.commons.Constants;
import com.tanhua.commons.exception.TanHuaException;
import com.tanhua.dubbo.api.db.UserInfoApi;
import com.tanhua.dubbo.api.mongo.PeachBlossomApi;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.mongo.PeachBlossom;
import com.tanhua.model.vo.PeachblossomSoundVo;
import com.tanhua.server.interceptor.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class PeachBlossomService {
    //从调度服务器获取，一个目标存储服务器，上传
    @Autowired
    private FastFileStorageClient client;

    @Autowired
    private FdfsWebServer webServer;// 获取存储服务器的请求URL

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private PeachBlossomApi peachBlossomApi;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private OssTemplate ossTemplate;

    /**
     *      发送传音
     *
     * @return
     */
    public void add(MultipartFile soundFile) {
        // 获取文件后缀名
        String filename = soundFile.getOriginalFilename();
        UserInfo userInfo = userInfoApi.getuserinfo(UserHolder.getUserId(), null);
        try {
            String upload = ossTemplate.upload(filename, soundFile.getInputStream());
            log.info(upload);
            PeachBlossom peachBlossom = new PeachBlossom();
            peachBlossom.setUserId(userInfo.getId());
            peachBlossom.setAge(userInfo.getAge().longValue());
            peachBlossom.setAvatar(userInfo.getAvatar());
            peachBlossom.setGender(userInfo.getGender());
            peachBlossom.setNickname(userInfo.getNickname());
            peachBlossom.setSoundUrl(upload);
            peachBlossomApi.add(peachBlossom);
        } catch (IOException e) {
            throw new TanHuaException("发送语音失败!");
        }

    }

    /**
     *      接收传音
     * @return
     */
    public PeachblossomSoundVo getSound() {
        //拼接KEY
        String key = Constants.USER_REMAINING_TIMES_KEY + UserHolder.getUserId();
        //判断缓存有没有记录，如果没有代表当天第一次登录
        Long decrement;
        if (!stringRedisTemplate.hasKey(key)) {
            Date date = null;
            try {
                //获取当天时间
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                date = sdf.parse(sdf.format(new Date()));

            } catch (ParseException e) {
                throw new TanHuaException("获取时间失败!");
            }
            //当天第一次登录，刷新次数,添加到缓存，设置过期时间为当天剩余秒数
            stringRedisTemplate.opsForValue().set(key,"10",24 * 60 * 60 - (System.currentTimeMillis() - date.getTime()) / 1000, TimeUnit.SECONDS);
            decrement = 10L;
        }else {
            //如果存在记录则判断次数是否大于零，如果大于零则表示当天还有次数
            long remainingTime = Long.parseLong(stringRedisTemplate.opsForValue().get(key));
            if (remainingTime >= 1) {
                //自减并返回最新值
                decrement = stringRedisTemplate.opsForValue().decrement(key);
            }else {
                decrement = 0L;
            }
        }
        //从缓存中查看已读取的传音
        List<String> ids = new ArrayList<>();
        String lookKey = "LOOK_SOUND_KEY_" + UserHolder.getUserId();
        if (stringRedisTemplate.hasKey(lookKey)){
            Set<String> members = stringRedisTemplate.opsForSet().members(lookKey);
            for (String member : members) {
                ids.add(member);
            }
        }
        UserInfo userInfo = userInfoApi.getuserinfo(UserHolder.getUserId(), null);
        PeachBlossom peachBlossom = peachBlossomApi.getSound(userInfo,ids);
        if (BeanUtil.isEmpty(peachBlossom)){
            throw new TanHuaException("没有更多传音，请稍后再试");
        }
        if(decrement != 0){
            stringRedisTemplate.opsForSet().add(lookKey,peachBlossom.getId().toString());
        }
        PeachblossomSoundVo init = PeachblossomSoundVo.init(peachBlossom);
        init.setRemainingTimes(decrement.intValue());

        return init;
    }
}
